{% extends "base.html" %}

{% block title %}数据可视化 - SurveyAnalyzer{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="{{ url_for('main.index') }}">
                <i class="fas fa-home me-1"></i>
                首页
            </a>
        </li>
        <li class="breadcrumb-item active" aria-current="page">
            <i class="fas fa-chart-pie me-1"></i>
            数据可视化
        </li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 图表类型选择 -->
    <div class="col-md-3 mb-4">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-palette me-2"></i>
                    图表类型
                </h6>
            </div>
            <div class="card-body">
                <div class="list-group list-group-flush">
                    <button class="list-group-item list-group-item-action" onclick="createChart('histogram')">
                        <i class="fas fa-chart-bar me-2"></i>
                        直方图
                    </button>
                    <button class="list-group-item list-group-item-action" onclick="createChart('scatter')">
                        <i class="fas fa-circle me-2"></i>
                        散点图
                    </button>
                    <button class="list-group-item list-group-item-action" onclick="createChart('pie')">
                        <i class="fas fa-chart-pie me-2"></i>
                        饼图
                    </button>
                     <button class="list-group-item list-group-item-action" onclick="createChart('heatmap')">
                         <i class="fas fa-th me-2"></i>
                         热力图
                     </button>
                </div>
            </div>
        </div>
        
        <!-- 图表配置 -->
        <div class="card mt-3">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-cog me-2"></i>
                    图表配置
                </h6>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="xColumn" class="form-label">X轴字段</label>
                    <select class="form-select" id="xColumn" onchange="autoUpdateChart()">
                        <option value="">请选择字段</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="yColumn" class="form-label">Y轴字段</label>
                    <select class="form-select" id="yColumn" onchange="autoUpdateChart()">
                        <option value="">请选择字段</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="colorColumn" class="form-label">颜色分组</label>
                    <select class="form-select" id="colorColumn" onchange="autoUpdateChart()">
                        <option value="">无分组</option>
                    </select>
                </div>
                <button class="btn btn-primary btn-sm" onclick="updateChart()">
                    <i class="fas fa-chart-bar me-1"></i>
                    生成图表
                </button>
            </div>
        </div>
    </div>
    
    <!-- 图表显示区域 -->
    <div class="col-md-9">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-chart-area me-2"></i>
                    图表展示
                </h5>
                <div>
                    <button class="btn btn-outline-primary btn-sm" onclick="downloadChart()">
                        <i class="fas fa-download me-1"></i>
                        下载图表
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" onclick="fullscreenChart()">
                        <i class="fas fa-expand me-1"></i>
                        全屏
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="chartContainer" style="height: 500px;">
                    <div class="d-flex align-items-center justify-content-center h-100 text-muted">
                        <div class="text-center">
                            <i class="fas fa-chart-bar fa-3x mb-3"></i>
                            <p>请选择图表类型开始可视化</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        

    </div>
</div>

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script>
let currentChartType = null;
let currentData = null;
const filename = '{{ filename }}';

// 页面加载时获取数据信息
document.addEventListener('DOMContentLoaded', function() {
    loadDataInfo();
});

function loadDataInfo() {
    fetch(`/api/data/${filename}`)
        .then(response => response.json())
        .then(data => {
            currentData = data;
            populateColumnSelects(data.columns);
        })
        .catch(error => {
            console.error('加载数据信息失败:', error);
        });
}

function populateColumnSelects(columns) {
    const selects = ['xColumn', 'yColumn', 'colorColumn'];
    
    selects.forEach(selectId => {
        const select = document.getElementById(selectId);
        // 临时移除事件监听器，避免在填充选项时触发autoUpdateChart
        const originalOnchange = select.onchange;
        select.onchange = null;
        
        select.innerHTML = selectId === 'colorColumn' ? '<option value="">无分组</option>' : '<option value="">请选择字段</option>';
        
        columns.forEach(column => {
            const option = document.createElement('option');
            option.value = column;
            option.textContent = column;
            select.appendChild(option);
        });
        
        // 恢复事件监听器
        select.onchange = originalOnchange;
    });
}

function createChart(chartType) {
    currentChartType = chartType;
    console.log('[DEBUG] createChart called with chartType:', chartType);
    console.log('[DEBUG] currentChartType set to:', currentChartType);
    

    
    // 根据图表类型调整字段选择
    adjustFieldSelection(chartType);
    
    // 对于需要字段选择的图表类型，不立即生成图表
    if (chartType === 'heatmap') {
        // 热力图不需要字段选择，直接生成
        generateChart();
    } else {
        // 其他图表类型需要用户选择字段后手动生成
        document.getElementById('chartContainer').innerHTML = `
            <div class="alert alert-info text-center">
                <i class="fas fa-info-circle me-2"></i>
                请选择相应的字段，然后点击"生成图表"按钮。
            </div>
        `;
    }
}

function adjustFieldSelection(chartType) {
    const xColumn = document.getElementById('xColumn');
    const yColumn = document.getElementById('yColumn');
    const colorColumn = document.getElementById('colorColumn');
    
    // 重置选择
    xColumn.disabled = false;
    yColumn.disabled = false;
    
    switch(chartType) {
        case 'histogram':
            yColumn.disabled = true;
            yColumn.value = '';
            // 不清空X轴字段，保持用户选择
            break;
        case 'scatter':
            // 散点图需要X轴和Y轴字段
            xColumn.disabled = false;
            yColumn.disabled = false;
            break;
        case 'pie':
            yColumn.disabled = true;
            yColumn.value = '';
            break;
        case 'heatmap':
            xColumn.disabled = true;
            yColumn.disabled = true;
            xColumn.value = '';
            yColumn.value = '';
            break;
    }
}

function generateChart() {
    if (!currentChartType) {
        console.log('[DEBUG] generateChart aborted: no currentChartType');
        return;
    }
    
    // 添加调试信息
    console.log('[DEBUG] generateChart called with currentChartType:', currentChartType);
    
    const chartData = {
        chart_type: currentChartType,
        x_column: document.getElementById('xColumn').value,
        y_column: document.getElementById('yColumn').value,
        color_column: document.getElementById('colorColumn').value
    };
    
    console.log('[DEBUG] chartData:', chartData);
    
    // 验证必要的字段
    if (currentChartType !== 'heatmap' && !chartData.x_column) {
        console.log('[DEBUG] generateChart aborted: missing x_column for', currentChartType);
        document.getElementById('chartContainer').innerHTML = `
            <div class="alert alert-warning text-center">
                <i class="fas fa-exclamation-triangle me-2"></i>
                请先选择X轴字段。
            </div>
        `;
        return;
    }
    
    // 散点图需要X轴和Y轴字段
    if (currentChartType === 'scatter' && (!chartData.x_column || !chartData.y_column)) {
        console.log('[DEBUG] generateChart aborted: missing x_column or y_column for scatter plot');
        document.getElementById('chartContainer').innerHTML = `
            <div class="alert alert-warning text-center">
                <i class="fas fa-exclamation-triangle me-2"></i>
                散点图需要选择X轴和Y轴字段。
            </div>
        `;
        return;
    }
    
    // 饼图需要X轴字段（分类字段）
    if (currentChartType === 'pie' && !chartData.x_column) {
        console.log('[DEBUG] generateChart aborted: missing x_column for pie chart');
        document.getElementById('chartContainer').innerHTML = `
            <div class="alert alert-warning text-center">
                <i class="fas fa-exclamation-triangle me-2"></i>
                饼图需要选择分类字段。
            </div>
        `;
        return;
    }
    

    
    // 显示加载状态
    document.getElementById('chartContainer').innerHTML = `
        <div class="d-flex align-items-center justify-content-center h-100">
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">生成图表中...</span>
                </div>
                <p class="mt-2">正在生成图表，请稍候...</p>
            </div>
        </div>
    `;
    
    fetch(`/api/visualize/${filename}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(chartData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            document.getElementById('chartContainer').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    图表生成失败：${data.error}
                </div>
            `;
        } else {
            // 显示base64编码的图片
            if (data.image_base64) {
                document.getElementById('chartContainer').innerHTML = `
                    <div class="text-center">
                        <img src="data:image/png;base64,${data.image_base64}" 
                             class="img-fluid" 
                             style="max-width: 100%; height: auto;" 
                             alt="生成的图表" />
                    </div>
                `;
            } else if (data.charts) {
                // 处理综合仪表板的多个图表
                let chartsHtml = '';
                Object.keys(data.charts).forEach(chartKey => {
                    const chart = data.charts[chartKey];
                    if (chart.image_base64) {
                        chartsHtml += `
                            <div class="mb-4">
                                <h6>${chart.title || chartKey}</h6>
                                <img src="data:image/png;base64,${chart.image_base64}" 
                                     class="img-fluid" 
                                     style="max-width: 100%; height: auto;" 
                                     alt="${chart.title || chartKey}" />
                            </div>
                        `;
                    }
                });
                document.getElementById('chartContainer').innerHTML = chartsHtml || `
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        图表生成完成，但没有可显示的内容。
                    </div>
                `;
            } else {
                document.getElementById('chartContainer').innerHTML = `
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        图表生成完成：${data.message || '成功'}
                    </div>
                `;
            }
        }
    })
    .catch(error => {
        document.getElementById('chartContainer').innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                图表生成失败：${error.message}
            </div>
        `;
    });
}

function updateChart() {
    generateChart();
}

function autoUpdateChart() {
    // 对于直方图，不自动更新，让用户手动点击生成按钮
    if (currentChartType && currentChartType !== 'histogram') {
        console.log('[DEBUG] autoUpdateChart called with currentChartType:', currentChartType);
        generateChart();
    } else {
        console.log('[DEBUG] autoUpdateChart skipped, currentChartType:', currentChartType);
    }
}

function downloadChart() {
    if (currentChartType) {
        const img = document.querySelector('#chartContainer img');
        if (img) {
            const link = document.createElement('a');
            link.download = `chart_${currentChartType}_${new Date().getTime()}.png`;
            link.href = img.src;
            link.click();
        } else {
            alert('没有可下载的图表');
        }
    }
}

function fullscreenChart() {
    const container = document.getElementById('chartContainer');
    if (container.requestFullscreen) {
        container.requestFullscreen();
    }
}
</script>
{% endblock %}